# 为 Windows 目标生成资源文件（包含版本信息和图标）
#
# 参数：
#   TARGET           - 目标名称（必须）
#   VERSION          - 版本号（格式：major[.minor[.patch[.build]]]）
#   COMPANY_NAME     - 公司名称
#   COPYRIGHT        - 版权信息
#   DESCRIPTION      - 文件描述
#   FILE_EXTENSION   - 文件扩展名（默认：exe）
#   ICONS            - 图标文件路径列表
#
# 用法示例：
# create_win32_resource_version(
#     TARGET MyApp
#     VERSION 2.1.0.15
#     COMPANY_NAME "My Company"
#     COPYRIGHT "Copyright © 2023 My Company"
#     DESCRIPTION "Awesome Application"
#     FILE_EXTENSION exe
#     ICONS
#         "${CMAKE_SOURCE_DIR}/assets/icon.ico"
#         "${CMAKE_SOURCE_DIR}/assets/logo.ico"
# )
#
# 简化版使用示例：
# create_win32_resource_version(
#     TARGET MyLibrary
#     VERSION 1.0.0
#     COMPANY_NAME "My Company"
#     COPYRIGHT "Copyright © 2023"
#     DESCRIPTION "My Shared Library"
# )
function(create_win32_resource_version)
    if(NOT MSVC)
        return() # 仅限 MSVC
    endif()

    # 参数解析
    set(options)
    set(oneValueArgs
        TARGET
        VERSION
        COMPANY_NAME
        COPYRIGHT
        DESCRIPTION
        FILE_EXTENSION
    )
    set(multiValueArgs ICONS)
    cmake_parse_arguments(ARGS "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})

    # 必需参数检查
    if(NOT ARGS_TARGET)
        message(FATAL_ERROR "create_win32_resource_version: TARGET argument is required")
    endif()
    if(NOT TARGET ${ARGS_TARGET})
        message(FATAL_ERROR "create_win32_resource_version: Target '${ARGS_TARGET}' does not exist")
    endif()

    # 默认值设置
    if(NOT ARGS_VERSION)
        set(ARGS_VERSION "1.0.0.0")
    endif()
    if(NOT ARGS_FILE_EXTENSION)
        set(ARGS_FILE_EXTENSION "exe")
    endif()

    # 版本号标准化
    string(REGEX MATCHALL "[0-9]+" version_parts "${ARGS_VERSION}")
    list(LENGTH version_parts version_length)
    while(version_length LESS 4)
        list(APPEND version_parts 0)
        math(EXPR version_length "${version_length} + 1")
    endwhile()
    list(GET version_parts 0 major)
    list(GET version_parts 1 minor)
    list(GET version_parts 2 patch)
    list(GET version_parts 3 build)
    set(FULL_VERSION "${major}.${minor}.${patch}.${build}")
    set(COMMA_VERSION "${major},${minor},${patch},${build}")

    # 生成资源文件路径
    set(RC_FILE "${CMAKE_CURRENT_BINARY_DIR}/${ARGS_TARGET}_res.rc")

    # 写入资源文件头
    file(WRITE "${RC_FILE}" "// Auto-generated by CMake - DO NOT EDIT!\n")
    file(APPEND "${RC_FILE}" "#pragma code_page(65001)\n\n") # 支持 UTF-8

    # 添加图标资源
    if(ARGS_ICONS)
        file(APPEND "${RC_FILE}" "// Icon Resources\n")
        set(icon_index 1)
        foreach(icon_path IN LISTS ARGS_ICONS)
            if(EXISTS "${icon_path}")
                file(APPEND "${RC_FILE}" "IDI_ICON${icon_index} ICON \"${icon_path}\"\n")
                math(EXPR icon_index "${icon_index} + 1")
            else()
                message(WARNING "Icon file not found: ${icon_path}")
            endif()
        endforeach()
        file(APPEND "${RC_FILE}" "\n")
    endif()

    # 版本信息块
    file(APPEND "${RC_FILE}" "// Version Information\n")
    file(APPEND "${RC_FILE}" "#include <winver.h>\n\n")
    file(APPEND "${RC_FILE}" "VS_VERSION_INFO VERSIONINFO\n")
    file(APPEND "${RC_FILE}" " FILEVERSION ${COMMA_VERSION}\n")
    file(APPEND "${RC_FILE}" " PRODUCTVERSION ${COMMA_VERSION}\n")
    file(APPEND "${RC_FILE}" " FILEFLAGSMASK 0x3fL\n")
    file(APPEND "${RC_FILE}" "#ifdef _DEBUG\n")
    file(APPEND "${RC_FILE}" " FILEFLAGS (VS_FF_DEBUG)\n")
    file(APPEND "${RC_FILE}" "#else\n")
    file(APPEND "${RC_FILE}" " FILEFLAGS 0x0L\n")
    file(APPEND "${RC_FILE}" "#endif\n")
    file(APPEND "${RC_FILE}" " FILEOS VOS_NT_WINDOWS32\n")

    # 根据目标类型设置文件类型
    get_target_property(target_type ${ARGS_TARGET} TYPE)
    if(target_type STREQUAL "SHARED_LIBRARY" OR target_type STREQUAL "MODULE_LIBRARY")
        set(ARGS_FILE_EXTENSION "dll")
        file(APPEND "${RC_FILE}" " FILETYPE VFT_DLL\n")
    else()
        file(APPEND "${RC_FILE}" " FILETYPE VFT_APP\n")
    endif()
    file(APPEND "${RC_FILE}" " FILESUBTYPE VFT2_UNKNOWN\n")
    file(APPEND "${RC_FILE}" "BEGIN\n")
    file(APPEND "${RC_FILE}" "    BLOCK \"StringFileInfo\"\n")
    file(APPEND "${RC_FILE}" "    BEGIN\n")
    file(APPEND "${RC_FILE}" "        BLOCK \"040904B0\"\n")
    file(APPEND "${RC_FILE}" "        BEGIN\n")
    file(APPEND "${RC_FILE}" "            VALUE \"CompanyName\", \"${ARGS_COMPANY_NAME}\\0\"\n")
    file(APPEND "${RC_FILE}" "            VALUE \"FileDescription\", \"${ARGS_DESCRIPTION}\\0\"\n")
    file(APPEND "${RC_FILE}" "            VALUE \"FileVersion\", \"${FULL_VERSION}\\0\"\n")
    file(APPEND "${RC_FILE}" "            VALUE \"LegalCopyright\", \"${ARGS_COPYRIGHT}\\0\"\n")
    file(APPEND "${RC_FILE}" "            VALUE \"OriginalFilename\", \"${ARGS_TARGET}.${ARGS_FILE_EXTENSION}\\0\"\n")
    file(APPEND "${RC_FILE}" "            VALUE \"ProductName\", \"${ARGS_TARGET}\\0\"\n")
    file(APPEND "${RC_FILE}" "            VALUE \"ProductVersion\", \"${FULL_VERSION}\\0\"\n")
    file(APPEND "${RC_FILE}" "        END\n")
    file(APPEND "${RC_FILE}" "    END\n")
    file(APPEND "${RC_FILE}" "    BLOCK \"VarFileInfo\"\n")
    file(APPEND "${RC_FILE}" "    BEGIN\n")
    file(APPEND "${RC_FILE}" "        VALUE \"Translation\", 0x409, 1200\n")
    file(APPEND "${RC_FILE}" "    END\n")
    file(APPEND "${RC_FILE}" "END\n")

    # 添加资源文件到目标
    target_sources(${ARGS_TARGET} PRIVATE "${RC_FILE}")

    # 设置目标属性
    if(target_type STREQUAL "EXECUTABLE")
        set_target_properties(${ARGS_TARGET} PROPERTIES
            WIN32_EXECUTABLE TRUE
            LINK_FLAGS "/MANIFEST:NO"
        )
    endif()

    # 显示生成信息
    message(STATUS "Generated Windows resource file: ${RC_FILE}")
endfunction()
